package com.lanhai.zhonglai.dispatch;
 
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; 
import org.springframework.stereotype.Service;
 
import com.lanhai.zhonglai.beans.AgvDataBean;

/**
 * 小车指令缓存
 *
 * @author zhengwei
 *
 */
@Service
public class AgvCmdMap {
	static Map<Integer, String> dispatchMap; // 指令处理锁 agv:1
	 
 
 

	static {
		dispatchMap =new  ConcurrentHashMap<Integer,String>(); 
	}

	private static final Logger logger = LogManager.getLogger("agvlog");

	//保存Agv，一条指令的处理的起始时间
	static Map<Integer, Long> timeMap = new ConcurrentHashMap<Integer, Long>( );

	/**
	 * 设置传输状态(皮带转动标识）
	 *
	 * @param agvid
	 * @param flag
	 */
	 

 
	/**
	 * 设置线程处理状态
	 *
	 * @param agvid
	 * @param flag
	 */
	public   synchronized void setDispatch(AgvDataBean agv , boolean flag) {
		long now=System.currentTimeMillis();
		if (flag) {
			//agv处理上锁
			timeMap.put(agv.getAgvId(), now);
			dispatchMap.put(agv.getAgvId(), "1");
  
		} else {
			//agv处理解锁
			
			String p=dispatchMap.get(agv.getAgvId());
			dispatchMap.put(agv.getAgvId(), "");
			if(p!=null&&p.equals("1")) {
				Long k = timeMap.get(agv.getAgvId());
				if (k != null) {
					Long t = now - k;
					if (t > 400) {
						// 200ms以上的需要记录
						logger.info(String.format("agv:%d执行时间:%d ms", agv.getAgvId(), t));
					}
				}
			} 
		}
	}

	/**
	 * 是否在其它线程处理中
	 *
	 * @param agvid
	 * @return
	 */
	public   boolean isDispatch(int agvid) {
		String m = dispatchMap.get(agvid);
		if (m == null || m.equals("1") == false) {
			return false;
		}
		return true;
	}
	
	 
}
